import { app, shell, BrowserWindow, ipcMain } from 'electron'
import UDPServer from './udp.server'
import { jspack } from 'jspack'
import FramePacker from './FramePacker'
import MotorServer from './MotorServer'


export default class NodeServer {
  public mainWindow: BrowserWindow
  private _server: UDPServer

  constructor(mainWindow) {
    this.mainWindow = mainWindow
    this._framePacker = new FramePacker()

    const msgDispatcher = (buffer) => {
      try {

        const headerBuffer = buffer.slice(0, 2)
        const bodyBuffer = buffer.slice(2, buffer.length - 1)

        const [header, cmd, identify, length, , bcc] = jspack.Unpack('>HHBH64sB', buffer)


        const data = buffer.slice(7, buffer.length - 1)
        return {
          header,
          cmd,
          identify,
          length,
          bcc,
          data,
        }
      } catch (error) {
        return null
      }
    }

    this._server = new UDPServer({
      port: 11110,
      host: '192.168.31.178',
      localPort: 11111,
      msgDispatcher
    })

    const escFrame = this._framePacker.map.GET_ECS_STATE
    this._server.on(`message:${escFrame.cmd.readUInt16BE()}`, (msg, rinfo) => {
      const result = this._framePacker.unpack(msg, escFrame)
      // console.log(`message:${escFrame.cmd.readUInt16BE()}------------------>> `, msg, result)
      if (this.mainWindow && !this.mainWindow.isDestroyed()) {

        this.mainWindow.webContents.send('GET_ECS_STATE', {
          voltage1: result.voltage1 / 1000,
          voltage2: result.voltage2 / 1000,
          voltage3: result.voltage3 / 1000,
          voltage4: result.voltage4 / 1000,
          voltage5: result.voltage5 / 1000,
          voltage6: result.voltage6 / 1000,
          electricity1: result.electricity1 / 1000,
          electricity2: result.electricity2 / 1000,
          temp1: result.temp1 / 1000,
          temp2: result.temp2 / 1000,
          cupTemp: result.cupTemp / 1000,
          charge: result.charge,
          dac: result.dac / 1000,
        })
      }

    })

    const motorFrame = this._framePacker.map.GET_MOTOR_STATE
    this._server.on(`message:${motorFrame.cmd.readUInt16BE()}`, (msg, rinfo) => {
      const result = this._framePacker.unpack(msg, motorFrame)
      // console.log(`message:${motorFrame.cmd.readUInt16BE()}------------------>> `, msg, result)
      if (this.mainWindow && !this.mainWindow.isDestroyed()) {
        this.mainWindow.webContents.send('GET_MOTOR_STATE', result)
      }
    })
  }

  create() {
    new MotorServer(this._server, this._framePacker, this.mainWindow)
  }

  close() {

    this._udpServer?.close()
  }
}
